package com.car.slave.im;

import static com.car.slave.im.model.user.IMAudioMessage.COLUMN_AUDIO_FILE_PATH;
import static com.car.slave.im.model.user.IMAudioMessage.COLUMN_AUDIO_FILE_URL;
import static com.car.slave.im.model.user.IMImageMessage.COLUMN_IMAGE_FILE_PATH;
import static com.car.slave.im.model.user.IMImageMessage.COLUMN_IMAGE_FILE_URL;
import static com.car.slave.im.model.user.IMTextMessage.COLUMN_MESSAGE_CONTENT;
import static com.car.slave.im.model.user.IMUserMessage.COLUMN_CREATE_TIME;
import static com.car.slave.im.model.user.IMUserMessage.COLUMN_MESSAGE_DIRECTION;
import static com.car.slave.im.model.user.IMUserMessage.COLUMN_MESSAGE_ID;
import static com.car.slave.im.model.user.IMUserMessage.COLUMN_MESSAGE_TYPE;
import static com.car.slave.im.model.user.IMUserMessage.COLUMN_READ_STATUS;
import static com.car.slave.im.model.user.IMUserMessage.COLUMN_SEND_STATUS;
import static com.car.slave.im.model.user.IMUserMessage.COLUMN_UESER_ID;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

import com.car.slave.im.model.user.IMAudioMessage;
import com.car.slave.im.model.user.IMImageMessage;
import com.car.slave.im.model.user.IMTextMessage;
import com.car.slave.im.model.user.IMUserMessage;

public class IMMessageManager extends SQLiteOpenHelper {
	
	private static final int DATABASE_VERSION = 3;
	private static final String TABLE_NAME = "message";
	
	private static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + COLUMN_UESER_ID + " TEXT, "
			+ COLUMN_MESSAGE_ID + " TEXT, " + COLUMN_MESSAGE_TYPE + " TEXT, " + COLUMN_MESSAGE_DIRECTION + " TEXT, "
			+ COLUMN_SEND_STATUS + " TEXT, " + COLUMN_READ_STATUS + " TEXT, " + COLUMN_MESSAGE_CONTENT + " TEXT, " 
			+ COLUMN_IMAGE_FILE_URL + " TEXT, "  + COLUMN_IMAGE_FILE_PATH + " TEXT, " + COLUMN_AUDIO_FILE_URL + " TEXT, "
			+ COLUMN_AUDIO_FILE_PATH + " TEXT, " + COLUMN_CREATE_TIME + " LONG);";
	private static final String TABLE_DROP = "DROP TABLE " + TABLE_NAME;
	
	private static IMMessageManager sInstance;
	public static synchronized IMMessageManager shareInstance(Context context) {
		if (null == sInstance) {
			sInstance = new IMMessageManager(context);
		}
		return sInstance;
	}
	
	public IMMessageManager(Context context) {
		super(context, getUserDatabaseName(context), null, DATABASE_VERSION);
		updateSendStatus(context);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL(TABLE_DROP);
		db.execSQL(TABLE_CREATE);
	}
	
	private static String getUserDatabaseName(Context context) {
        String path = new File(getAppPath(context), "chezhil_im.db").getAbsolutePath();
        return path;
    }
	
	private static File getAppPath(Context context) {
		File rootFile;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			rootFile = Environment.getExternalStorageDirectory();
		} else {
			rootFile = context.getExternalCacheDir();
		}
		File packFile = new File(rootFile, "车知了_IM");
		if (!packFile.exists()) {
			packFile.mkdir();
		}
		return packFile;
	}
	
	/**
	 * 获取最近的消息记录.notice会将所有未读的信息标示为已读.
	 * @param count
	 * @return
	 */
	public List<IMUserMessage> getRecentMessages(Context context, int count) {
		updateReadStatus(context);
		
		List<IMUserMessage> messages = new ArrayList<IMUserMessage>();
		SQLiteDatabase db = getReadableDatabase();
		Cursor c = db.query(TABLE_NAME, null, COLUMN_UESER_ID + "=?", new String[]{IMClient.shareInstance().getUin(context)}, 
				null, null, COLUMN_CREATE_TIME + " DESC"/**ASC**/, String.valueOf(count));
		if (c.moveToLast()) {
			messages.add(getMessageByCursor(c));
		}
		while (c.moveToPrevious()) {
			messages.add(getMessageByCursor(c));
		}
		c.close();
		return messages;
	}
	
	/**
	 * 获取未读信息的条数.
	 * @return
	 */
	public int getUnReadCount(Context context) {
		SQLiteDatabase db = getReadableDatabase();
		Cursor c = db.query(TABLE_NAME, null, COLUMN_UESER_ID + "=? and " + COLUMN_READ_STATUS + "=?", 
				new String[]{IMClient.shareInstance().getUin(context), String.valueOf("0")}, null, null, null, null);
		int count = c.getCount();
		c.close();
		return count;
	}
	
	public IMUserMessage getMessageById(Context context, String msgId) {
		SQLiteDatabase db = getReadableDatabase();
		Cursor c = db.query(TABLE_NAME, null, COLUMN_UESER_ID + "=? and " + COLUMN_MESSAGE_ID + "=?", 
				new String[]{IMClient.shareInstance().getUin(context), msgId}, null, null, null);
		IMUserMessage message = null;
		if (c.moveToNext()) {
			message = getMessageByCursor(c);
		}
		c.close();
		return message;
	}
	
	public void saveMessage(Context context, IMUserMessage msg) {
		// 设置消息id
		msg.userId = IMClient.shareInstance().getUin(context);

		ContentValues cv = msg.getContentValues();
		if (null == getMessageById(context, msg.messageId)) {
			SQLiteDatabase db = getWritableDatabase();
			db.insert(TABLE_NAME, null, cv);
		} else {
			updateMessage(context, msg);
		}
	}
	
	/**
	 * 批量保存信息.
	 * @param msgs
	 */
	public void saveMessages(Context context, List<IMUserMessage> msgs) {
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		try {
			for (IMUserMessage msg : msgs) {
				saveMessage(context, msg);
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}
	
	public void updateMessage(Context context, IMUserMessage msg) {
		SQLiteDatabase db = getWritableDatabase();
		ContentValues cv = msg.getContentValues();
		db.update(TABLE_NAME, cv,COLUMN_UESER_ID + "=? and " + COLUMN_MESSAGE_ID + "=?", 
				new String[]{IMClient.shareInstance().getUin(context), msg.messageId});
	}
	
	// 将所有发送中的信息更新到发送失败.
	private void updateSendStatus(Context context) {
		SQLiteDatabase db = getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(COLUMN_SEND_STATUS, "1");
		db.update(TABLE_NAME, cv, COLUMN_UESER_ID + "=?and " + COLUMN_SEND_STATUS + "=?", new String[]{
				IMClient.shareInstance().getUin(context), "0"});
	}
	
	// 将所有消息标示为已读.
	private void updateReadStatus(Context context) {
		SQLiteDatabase db = getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(COLUMN_READ_STATUS, "1");
		db.update(TABLE_NAME, cv, COLUMN_UESER_ID + "=?", new String[]{IMClient.shareInstance().getUin(context)});
	}
	
	private IMUserMessage getMessageByCursor(Cursor c) {
		IMUserMessage message = new IMTextMessage();
		int type = c.getInt(c.getColumnIndex(COLUMN_MESSAGE_TYPE));
		switch (type) {
		case IMUserMessage.TYPE_TEXT:
			message = new IMTextMessage();
			break;
		case IMUserMessage.TYPE_IMAGE:
			message = new IMImageMessage();
			break;
		case IMUserMessage.TYPE_VOICE:
			message = new IMAudioMessage();
			break;
		default:
			break;
		}
		message.cursorToMessage(c);
		return message;
	}
}
